package api

import (
	"encoding/json"
	"errors"
	"fmt"
	"local/model"
	"strings"

	"github.com/jinzhu/gorm"
	"github.com/raintean/blink"
)

func handleUrl(url string) string {
	return strings.ReplaceAll(url, "/", "_")
}
func getList(str string) (res string, err error) {
	var parent model.GetList
	var parents []model.Person
	err = json.Unmarshal([]byte(str), &parent)
	if err != nil || parent.Parent == 0 {
		return res, errors.New("参数错误")
	}
	result := model.DB.Model(&model.Person{}).Order(`"order" asc`).Find(&parents, "parent=? and uid=?", parent.Parent, parent.Uid)
	fmt.Println(result.Error)
	r, _ := json.Marshal(parents)
	res = string(r)
	return
}

func Register(view *blink.WebView) {
	// 登录
	view.Inject(handleUrl(`/api/web/user/login`), func(str string) (string, error) {
		var user model.User
		err := json.Unmarshal([]byte(str), &user)
		if len(user.Tel) == 0 || len(user.Password) == 0 || err != nil {
			return "", errors.New("手机号和密码不能为空")
		}
		var u model.User
		model.DB.First(&u, "tel=?", user.Tel)
		if len(u.Tel) == 0 || len(u.Password) == 0 {
			return "", errors.New("用户不存在")
		}
		if _, err := model.ValidatePassword(user.Password, u.Password); err != nil {
			return "", errors.New("密码错误")
		}
		u.Password = ""
		res, _ := json.Marshal(u)
		return string(res), err
	})

	// 退出登录
	view.Inject(handleUrl(`/api/web/loginout`), func() bool {
		return true
	})

	// 注册
	view.Inject(handleUrl(`/api/web/user/register`), func(str string) (string, error) {
		var user model.User
		err := json.Unmarshal([]byte(str), &user)
		if len(user.Tel) == 0 || len(user.Password) == 0 || len(user.Name) == 0 || err != nil {
			return "", errors.New("手机号、密码、姓名不能为空")
		}

		var u model.User
		model.DB.First(&u, "tel=?", user.Tel)
		if len(u.Tel) > 0 || len(u.Password) > 0 {
			return "", errors.New("手机号已被注册")
		}
		p, err := model.GeneratePassword(user.Password)
		if err != nil {
			return "", err
		}
		user.Password = string(p)
		model.DB.Create(&user)
		// 清除返回给前端的密码
		user.Password = ""
		res, _ := json.Marshal(user)
		fmt.Println(user, str)
		return string(res), err
	})

	// 根据id获取自己的用户信息
	view.Inject(handleUrl(`/api/web/user/info`), func(str string) (res string, err error) {
		var uid model.Uid
		err = json.Unmarshal([]byte(str), &uid)
		if err != nil || uid.ID == 0 {
			return res, errors.New("参数错误")
		}
		var u model.User
		model.DB.First(&u, "id=?", uid.ID)
		if len(u.Tel) == 0 || len(u.Password) == 0 {
			return "", errors.New("用户不存在")
		}
		u.Password = ""
		r, _ := json.Marshal(u)
		res = string(r)
		return
	})

	// 获取列表
	view.Inject(handleUrl(`/api/app/person/list`), getList)
	// 公开数据获取列表
	view.Inject(handleUrl(`/api/web/person/list`), getList)

	// 新建数据
	view.Inject(handleUrl(`/api/app/person/add`), func(str string) (res string, err error) {
		var p model.Person
		err = json.Unmarshal([]byte(str), &p)
		if err != nil {
			return res, err
		}

		model.DB.Create(&p)
		r, _ := json.Marshal(p)
		res = string(r)
		if p.Parent != -1 {
			// 父节点需要加一
			var person model.Person
			model.DB.Model(&person).Where("id = ?", p.Parent).Update(map[string]model.Any{"childs": gorm.Expr("childs + ?", 1)})
		}
		return
	})

	// 查询单个数据
	view.Inject(handleUrl(`/api/app/person/info`), func(str string) (res string, err error) {
		var uid model.Uid
		err = json.Unmarshal([]byte(str), &uid)
		if err != nil || uid.ID == 0 {
			return res, errors.New("参数错误")
		}
		var u model.Person
		model.DB.First(&u, "id=?", uid.ID)
		r, _ := json.Marshal(u)
		res = string(r)
		return
	})

	// 编辑更新数据
	view.Inject(handleUrl(`/api/app/person/update`), func(str string) (res string, err error) {
		var m = make(map[string]interface{})
		err = json.Unmarshal([]byte(str), &m)
		if err != nil {
			return
		}
		id, ok := m["id"]
		if ok == false {
			id, ok = m["ID"]
			if ok == false {
				return res, errors.New("id不能为空")
			}
		}
		// 删掉属性
		delete(m, "id")
		delete(m, "ID")

		// 先查询出数据,如果paranet 存在，则可能被修改
		parent, ok := m["parent"]
		if ok {
			var p model.Person
			model.DB.First(&p, "id=?", id)
			if p.Parent != parent {
				// 不存在，则更新
				if parent != -1 {
					model.DB.Model(&model.Person{}).Where("id = ?", parent).Update(map[string]model.Any{"childs": gorm.Expr("childs + ?", 1)})
				}
				if p.Parent != -1 {
					model.DB.Model(&model.Person{}).Where("id = ?", p.Parent).Update(map[string]model.Any{"childs": gorm.Expr("childs - ?", 1)})
				}
			}
		}

		model.DB.Model(&model.Person{}).Where("id=?", id).Update(m)
		return
	})

	// 删除
	view.Inject(handleUrl(`/api/app/person/remove`), func(str string) (res string, err error) {
		var uid model.Uid
		err = json.Unmarshal([]byte(str), &uid)
		if err != nil || uid.ID == 0 {
			return res, errors.New("参数错误")
		}
		var person model.Person
		model.DB.First(&person, "id=?", uid.ID)
		// 父节点减一
		if person.Parent != -1 {
			model.DB.Model(&person).Where("id = ?", person.Parent).Update(map[string]model.Any{"childs": gorm.Expr("childs - ?", 1)})
		}

		// 子节点的 parent 需要变为 -1
		model.DB.Model(&model.Person{}).Where("parent=?", uid.ID).Updates(map[string]model.Any{"parent": -1})

		model.DB.Where("id = ?", uid.ID).Unscoped().Delete(&model.Person{})
		return
	})

	// 更新顺序
	view.Inject(handleUrl(`/api/app/person/updateOrders`), func(str string) (res string, err error) {
		var m model.UpdateOrders
		err = json.Unmarshal([]byte(str), &m)
		fmt.Println(m)
		for _, v := range m.List {
			fmt.Println(v)
			model.DB.Model(&model.Person{}).Where("id = ?", v.Id).Update(map[string]model.Any{"order": v.Order})
		}
		return
	})
}
